// dh-banner-cache-updater 云对象
// Banner缓存更新器

const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
	/**
	 * 更新所有banner的缓存
	 * 建议每小时执行一次
	 */
	async updateAllCaches() {
		try {
			// 1. 获取所有需要缓存的banner（引用类型 + 缓存策略）
			const bannersRes = await db.collection('dh-hospital_banners')
				.where({
					content_type: dbCmd.neq('custom'),
					cache_strategy: 'cache'
				})
				.get()
			
			const banners = bannersRes.data || []
			
			if (banners.length === 0) {
				return {
					code: 200,
					message: '没有需要缓存的banner',
					data: { total: 0, updated: 0, failed: 0 }
				}
			}
			
			// 2. 逐个更新缓存
			let updatedCount = 0
			let failedCount = 0
			const failedBanners = []
			
			for (const banner of banners) {
				try {
					const cacheData = await this._fetchContentForCache(banner)
					
					if (cacheData) {
						// 更新缓存
						await db.collection('dh-hospital_banners')
							.doc(banner._id)
							.update({
								cache_data: {
									...cacheData,
									cached_at: Date.now()
								},
								is_orphan: false,
								orphan_reason: ''
							})
						
						updatedCount++
					} else {
						// 缓存失败，标记为孤立
						await db.collection('dh-hospital_banners')
							.doc(banner._id)
							.update({
								is_orphan: true,
								orphan_reason: '缓存更新时发现关联内容不存在',
								orphan_check_time: Date.now()
							})
						
						failedCount++
						failedBanners.push({
							_id: banner._id,
							content_type: banner.content_type,
							content_id: banner.content_id
						})
					}
				} catch (err) {
					console.error(`更新banner ${banner._id} 缓存失败:`, err)
					failedCount++
					failedBanners.push({
						_id: banner._id,
						error: err.message
					})
				}
			}
			
			return {
				code: 200,
				message: `缓存更新完成：成功${updatedCount}个，失败${failedCount}个`,
				data: {
					total: banners.length,
					updated: updatedCount,
					failed: failedCount,
					failedBanners
				}
			}
		} catch (err) {
			console.error('缓存更新失败:', err)
			return {
				code: 500,
				message: err.message || '缓存更新失败',
				data: null
			}
		}
	},
	
	/**
	 * 更新单个banner的缓存
	 */
	async updateSingleCache(bannerId) {
		try {
			// 1. 获取banner信息
			const bannerRes = await db.collection('dh-hospital_banners')
				.doc(bannerId)
				.get()
			
			const banner = bannerRes.data?.[0]
			
			if (!banner) {
				return { code: 404, message: 'Banner不存在' }
			}
			
			if (banner.content_type === 'custom') {
				return { code: 400, message: '自定义banner不需要缓存' }
			}
			
			// 2. 获取并缓存内容
			const cacheData = await this._fetchContentForCache(banner)
			
			if (!cacheData) {
				// 标记为孤立
				await db.collection('dh-hospital_banners')
					.doc(bannerId)
					.update({
						is_orphan: true,
						orphan_reason: '关联内容不存在',
						orphan_check_time: Date.now()
					})
				
				return { code: 404, message: '关联内容不存在' }
			}
			
			// 3. 更新缓存
			await db.collection('dh-hospital_banners')
				.doc(bannerId)
				.update({
					cache_data: {
						...cacheData,
						cached_at: Date.now()
					},
					is_orphan: false,
					orphan_reason: ''
				})
			
			return {
				code: 200,
				message: '缓存更新成功',
				data: cacheData
			}
		} catch (err) {
			console.error('更新单个缓存失败:', err)
			return {
				code: 500,
				message: err.message
			}
		}
	},
	
	/**
	 * 清除过期缓存
	 * @param {number} hoursAgo - 清除多少小时前的缓存
	 */
	async clearExpiredCaches(hoursAgo = 24) {
		try {
			const expireTime = Date.now() - (hoursAgo * 60 * 60 * 1000)
			
			const result = await db.collection('dh-hospital_banners')
				.where({
					'cache_data.cached_at': dbCmd.lt(expireTime)
				})
				.update({
					cache_data: dbCmd.remove()
				})
			
			return {
				code: 200,
				message: `已清除 ${result.updated || 0} 个过期缓存`
			}
		} catch (err) {
			return {
				code: 500,
				message: err.message
			}
		}
	},
	
	/**
	 * 强制刷新所有缓存（包括未过期的）
	 */
	async forceRefreshAll() {
		return await this.updateAllCaches()
	},
	
	// ========== 内部辅助方法 ==========
	
	/**
	 * 获取需要缓存的内容
	 */
	async _fetchContentForCache(banner) {
		let collection, fieldMap
		
		switch (banner.content_type) {
			case 'promotion':
				collection = 'dh-hospital_promotions'
				fieldMap = { 
					title: true, 
					description: true, 
					image: true,
					status: true,
					start_date: true,
					end_date: true
				}
				break
			case 'service':
				collection = 'dh-services'
				fieldMap = { 
					service_name: true, 
					description: true, 
					image: true,
					status: true
				}
				break
			case 'product':
				collection = 'dh-products'
				fieldMap = { 
					product_name: true, 
					description: true, 
					image: true,
					status: true
				}
				break
			default:
				return null
		}
		
		try {
			const res = await db.collection(collection)
				.doc(banner.content_id)
				.field(fieldMap)
				.get()
			
			const data = res.data?.[0]
			
			if (!data || (data.status && data.status !== 1)) {
				return null
			}
			
			// 返回标准化的缓存数据
			return {
				title: data.title || data.service_name || data.product_name,
				description: data.description || '',
				image: this._extractImageUrl(data.image),
				source_status: data.status,
				source_start_date: data.start_date,
				source_end_date: data.end_date
			}
		} catch (err) {
			console.error('获取内容失败:', err)
			return null
		}
	},
	
	/**
	 * 提取图片URL
	 */
	_extractImageUrl(imageData) {
		if (!imageData) return ''
		if (typeof imageData === 'string') return imageData
		if (typeof imageData === 'object' && imageData.url) return imageData.url
		if (Array.isArray(imageData) && imageData.length > 0) {
			const first = imageData[0]
			return typeof first === 'string' ? first : (first.url || '')
		}
		return ''
	}
}

